import React, { Component } from 'react'

import { reqCategory, reqUpdateCategory, reqAddCategory } from '../../api/admin.js'

import AddFrom from './AddForm'
import UpdateForm from './UpdateForm'

import {
  Card,
  Button,
  Table,
  Space,
  message,
  Modal
} from 'antd';
import { PlusOutlined, ArrowRightOutlined } from '@ant-design/icons';

export default class Category extends Component {

  UNSAFE_componentWillMount () {
    this.initColumns()
  }

  componentDidMount () {
    this.getCategorys()
  }

  state = {
    categorys: [], // 一级分类列表
    subCategorys: [], // 二级分类列表
    loading: false,
    parentId: '0', // 当前需要显示的分类列表的父分类ID
    parentName: '', // 当前需要显示的分类列表的父分类名称
    showStatus: 0  //0代表关闭，1代表添加，2代表更新
  }

  //初始化table所有列的数组
  initColumns = () => {
    this.columns = [
      {
        title: '分类的名称',
        dataIndex: 'name'
      },
      {
        title: '操作',
        width: 300,
        render: (category) => (
          <Space size="middle">
            <Button type="link" onClick={() => this.updateShow(category)}>
              修改分类
            </Button>
            {
              this.state.parentId === '0' ?
                <Button type="link" onClick={() => this.showSubCategorys(category)}>
                  查看子分类
              </Button> : null
            }

          </Space>
        ),
      }
    ];
  }

  //请求获取一级/二级分类列表
  getCategorys = async (parentId) => {
    this.setState({ loading: true })
    parentId = parentId || this.state.parentId
    const result = await reqCategory(parentId)
    this.setState({ loading: false })
    if (result.status === 0) {
      // 取出分类数组(可能是一级也可能二级的)
      const categorys = result.data
      if (parentId === '0') {
        // 更新一级分类状态
        this.setState({
          categorys
        })
        console.log('----', this.state.categorys.length)
      } else {
        // 更新二级分类状态
        this.setState({
          subCategorys: categorys
        })
      }
    } else {
      message.error('获取一级分类列表失败')
    }
  }

  showSubCategorys = (category) => {
    console.log(category);
    this.setState({
      parentId: category._id,
      parentName: category.name
    }, () => {
      this.getCategorys()
    })

  }

  showCategorys = () => {
    this.setState({
      parentId: '0',
      parentName: '',
      subCategorys: []
    })
  }

  // 添加分类
  addCategory = () => {
    this.form
      .validateFields()
      .then(async (values) => {
        console.log(values);
        this.setState({
          showStatus: 0
        })
        const { categoryName, parentId } = values
        const result = await reqAddCategory({ parentId, categoryName })
        if (result.status === 0) {
          message.success("添加分类成功")
          if (parentId === this.state.parentId) {
            this.getCategorys()
          } else if (parentId === '0') {
            this.getCategorys('0')
          }

        }
      }).catch((err) => {
        message.error("请输入分类名称")
      })
  }

  //显示添加modal
  addShow = () => {
    this.setState({
      showStatus: 1
    })
  }

  //更新分类
  updateCategory = () => {
    this.form
      .validateFields()
      .then(async (values) => {
        console.log(values);
        this.setState({
          showStatus: 0
        })
        const categoryId = this.category._id
        const { categoryName } = values
        const result = await reqUpdateCategory({ categoryId, categoryName })
        if (result.status === 0) {
          this.getCategorys()
        }
      }).catch((err) => {
        message.error("请输入分类名称")
      })
  }

  //显示更新modal
  updateShow = (category) => {
    this.category = category
    this.setState({
      showStatus: 2
    })
  }

  //关闭modal
  handleCancel = () => {
    this.setState({
      showStatus: 0
    })
  }

  setForm = (form) => {
    this.form = form
    console.log(this.form);
  }

  render () {

    const { categorys, loading, parentId, parentName, subCategorys, showStatus } = this.state

    const category = this.category || {}
    console.log(category);
    const title = parentId === '0' ? "一级分类列表" : (
      <span>
        <Button type="link" onClick={this.showCategorys}>一级分类列表</Button>
        <ArrowRightOutlined />
        <span style={{ marginLeft: 10 }}>{parentName}</span>
      </span>
    )
    const extra = (
      < Button type="primary" icon={< PlusOutlined />} onClick={this.addShow}>
        添加
      </ Button>
    )

    return (
      <Card size="small" title={title} extra={extra} >
        <Table
          dataSource={parentId === '0' ? categorys : subCategorys}
          columns={this.columns}
          bordered
          rowKey="_id"
          pagination={{ defaultPageSize: 5, showQuickJumper: true }}
          loading={loading}
        />
        <Modal
          title="添加分类"
          destroyOnClose
          visible={showStatus === 1}
          onOk={this.addCategory}
          onCancel={this.handleCancel}
        >
          <AddFrom categorys={categorys} parentId={parentId} setForm={this.setForm} />
        </Modal>
        {/* 
        {
          showStatus === 2 ? <Modal
            title="更新分类"
            visible={showStatus === 2}
            onOk={this.updateCategory}
            onCancel={this.handleCancel}
          >
            <UpdateForm
              categoryName={category.name}
              setForm={this.setForm}
            />
          </Modal> : null
        }
        */}
        <Modal
          title="更新分类"
          destroyOnClose
          visible={showStatus === 2}
          onOk={this.updateCategory}
          onCancel={this.handleCancel}
        >
          <UpdateForm
            categoryName={category.name}
            setForm={this.setForm}
          />
        </Modal>
      </Card>
    )
  }
}
